import React from "react";
import { LgTable, LgTableProps, LgButton, LgSwitch, lgAlert, LgAlertMouldA, LgCheckbox, LgRadio } from "lancoo-web-ui";
import { Popover } from 'antd';
import moment from "moment";
import { Scrollbars } from 'react-custom-scrollbars';
import styles from "./index.module.scss";
import './LgTable.scss'

const Base = (props) => {
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
  const isManage = sessionStorage.getItem('isManage');

  const alertPersonArrangement = (id, type) => {
    let alert = lgAlert.show({
      duration: 0,
      content: `确定要${type === 'del' ? '删除' : '撤回'}该值周人员安排吗？`,
      isShowCloseBtn: true,
      tipType: 'question',
      tipSize: 'small',
      tipMouldType: 'A',
      confirmText: "确定",
      closeText: "再想想",
      showCover: true,
      coverZIndex: 1000,
      coverOpacity: 0.25,
      onConfirm: () => {
        if (type === 'del') {
          props.deletePerson(id);
        } else {
          props.recallPerson(id);
        }

        lgAlert.close(alert.index);
      }
    });
  }

  const delWeek = (idx, type) => {
    let alert = lgAlert.show({
      duration: 0,
      content: `确定要${type === 'del' ? '删除' : '撤回'}该周次信息吗？`,
      isShowCloseBtn: true,
      tipType: 'question',
      tipSize: 'small',
      tipMouldType: 'A',
      confirmText: "确定",
      closeText: "再想想",
      showCover: true,
      coverZIndex: 1000,
      coverOpacity: 0.25,
      onConfirm: () => {
        if (type === 'del') {
          props.deleteWeek(idx, 'aKeyDel');
        } else {
          props.recallPerson(idx);
        }
        lgAlert.close(alert.index);
      }
    });
  }

  const delRemindItem = (idx, type) => {
    let alert = lgAlert.show({
      duration: 0,
      content: `确定要${type === 'delRemindItem' ? '删除' : '撤回'}该提醒吗？`,
      isShowCloseBtn: true,
      tipType: 'question',
      tipSize: 'small',
      tipMouldType: 'A',
      confirmText: "确定",
      closeText: "再想想",
      showCover: true,
      coverZIndex: 1000,
      coverOpacity: 0.25,
      onConfirm: () => {
        if (type === 'delRemindItem') {
          props.delRemindItem(idx);
        } else {
          props.recallPerson(idx);
        }
        lgAlert.close(alert.index);
      }
    });
  }

  let data = [];
  let dataOne = {};

  let columns = [
    {
      title: "周次",
      width: 61,
      dataIndex: "weekNo",
      key: "weekNo",
      align: "center",
      // className: "type-header",
      render: (value) => {
        return <span className={"template_span"}>{value}</span>;
      },
    },
    {
      title: "日期",
      width: 200,
      dataIndex: "days",
      key: "days",
      align: "center",
      render: (value) => {
        return <span className={"template_span days_span"} title={value} style={{ width: !(userInfo.userType === '6' || (userInfo.userType === '0' && (userInfo.userClass === '2' || userInfo.userClass === '4'))) ? '227px' : '' }} >{value}</span>;
      },
    },
    {
      title: "值周组长",
      width: 100,
      dataIndex: "grouper",
      key: "grouper",
      align: "center",
      render: (value) => {
        return <span className={"template_span"} title={value}>{value}</span>;
      },
    },
    {
      title: "值周人员",
      width: 302,
      // marginLeft: '29px',
      dataIndex: "grouperPerson",
      key: "grouperPerson",
      align: "center",
      render: (value, record) => {
        // return <span className={"template_span person_list"} title={value}>{value}</span>;
        return <span style={{ display: 'flex', color: '#333', whiteSpace: 'nowrap' }}><span className={"template_span person_list "} title={value}>{value}</span><span> {value.length > 34 && record.personNum ? `等${record.personNum}人` : ''}</span></span>;
      },
    }
  ];

  if (sessionStorage.getItem('isAdvanced') == 0 && !(userInfo.userType === '6' || (userInfo.userType === '0' && (userInfo.userClass === '2' || userInfo.userClass === '4')))) {
    columns.splice(5)
  }

  if (props.type === 'template') {

    // 假设当前时间为
    // 获取当前日期
    let currentDate = new Date();

    // 获取当前日期是星期几 (0 表示星期日, 1 表示星期一, ..., 6 表示星期六)
    let currentDay = currentDate.getDay();

    // 计算距离上一个周一的天数差值
    let daysToMonday = currentDay === 0 ? 6 : currentDay - 1; // 如果当前是周日，距离上一个周一是6天，否则就是当前星期几减1

    // 设置当前日期为周一的日期
    let mondayDate = new Date(currentDate);
    mondayDate.setDate(currentDate.getDate() - daysToMonday);

    // 创建新的 dataOne 对象
    // let dataOne = {
    //   key: 1,
    //   weekNo: 1,
    //   days: `${formatDate(mondayDate)}~${formatDate(addDays(mondayDate, 6))}`,
    //   grouper: '老师1',
    //   grouperPerson: '值周老师1，值周老师2，值周老师3',
    // };
    // data.push(dataOne)

    // 确保 data 数组长度为 8
    while (data.length < 8) {
      let newDataOne = {
        key: data.length + 1,
        weekNo: data.length + 1,
        days: `${formatDate(addDays(mondayDate, (data.length) * 7))}~${formatDate(addDays(mondayDate, (data.length + 1) * 6))}`,
        grouper: '老师' + (data.length + 1),
        grouperPerson: '',
        quest1: '老师' + (data.length + 1),
        quest2: '老师' + (data.length + 1),
        quest3: '老师' + (data.length + 1),
        quest4: '老师' + (data.length + 1),
      };

      // 模拟示例中的值周老师信息
      newDataOne.grouperPerson = `值周老师${(data.length + 1) * 3 - 2}，值周老师${(data.length + 1) * 3 - 1}，值周老师${(data.length + 1) * 3}`;

      // 添加到 data 数组
      data.push(newDataOne);
    }


    if (props.templateType === 1) {
      columns.splice(3, 1)
      let questArr = [
        {
          title: "早上入校",
          width: 80,
          dataIndex: "quest1",
          key: "quest1",
          align: "center",
          render: (value) => {
            return <span className={"template_span"}>{value}</span>;
          },
        },
        {
          title: "大课间",
          width: 80,
          dataIndex: "quest2",
          key: "quest2",
          align: "center",
          render: (value) => {
            return <span className={"template_span"}>{value}</span>;
          },
        },
        {
          title: "午餐",
          width: 80,
          dataIndex: "quest3",
          key: "quest3",
          align: "center",
          render: (value) => {
            return <span className={"template_span"}>{value}</span>;
          },
        },
        {
          title: "下午放学",
          width: 95,
          dataIndex: "quest4",
          key: "quest4",
          align: "center",
          render: (value) => {
            return <span className={"template_span"}>{value}</span>;
          },
        },
      ]
      columns = [...columns, ...questArr];
    }

    if (!props.setGrouper) {
      columns.splice(2, 1)
    }
  } else if (props.type === 'templateDay') {

    // 假设当前时间为
    // 获取当前日期
    let currentDate = new Date();

    // 获取当前日期是星期几 (0 表示星期日, 1 表示星期一, ..., 6 表示星期六)
    let currentDay = currentDate.getDay();

    // 计算距离上一个周一的天数差值
    let daysToMonday = currentDay === 0 ? 6 : currentDay - 1; // 如果当前是周日，距离上一个周一是6天，否则就是当前星期几减1

    // 设置当前日期为周一的日期
    let mondayDate = new Date(currentDate);
    mondayDate.setDate(currentDate.getDate() - daysToMonday);

    let dutyArr = ['心理教育工作', '辅导员事务', '学生公寓管理事务', '学生中心事务', '思想政治教育', '学生奖励事务', '发展部办公室事务', '学生教育、活动等事务']
    // 确保 data 数组长度为 8
    while (data.length < 8) {
      let dayOfWeek = data.length < 7 ? '周' + '一二三四五六日'[data.length] : '周一';
      let newDataOne = {
        key: data.length + 1,
        weekNo: data.length + 1,
        days: `${formatDate(addDays(mondayDate, (data.length) * 7))}~${formatDate(addDays(mondayDate, (data.length + 1) * 6))}`,
        group: '人员' + (data.length + 1) + '组',
        grouperPerson: '',
        quest1: '老师' + (data.length + 1),
        quest2: '老师' + (data.length + 3),
        quest3: '老师' + (data.length + 1),
        quest4: '老师' + (data.length + 3),
        quest5: '老师' + (data.length + 1),
        quest6: '老师' + (data.length + 3),
        quest7: '老师' + (data.length + 1),
        day: `${formatDate(addDays(mondayDate, (data.length)))}    ${dayOfWeek}`,
        dutyContent: dutyArr[data.length],
      };
      // 设置值日老师信息
      let groupIndex = Math.floor(data.length) % 2; // 根据 data.length 确定当前是第几组值日老师
      if (groupIndex === 0) {
        // 第一组值日老师
        newDataOne.grouperPerson = `值日老师1，值日老师2，值日老师3`;
      } else {
        // 第二组值日老师
        newDataOne.grouperPerson = `值日老师4，值日老师5，值日老师6`;
      }
      newDataOne.grouperPersonPhone = `值日老师${(data.length + 1)}      1357754125${data.length + 1}`

      // 添加到 data 数组
      data.push(newDataOne);
    }


    if (props.templateType === 0) {
      let questArr = [];
      let obj = [
        {
          title: `组别`,
          width: 80,
          dataIndex: `group`,
          key: `group`,
          align: "center",
          render: (value) => {
            return <span className={"template_span"}>{value}</span>;
          },
        }
      ]
      // 生成从周一到周日的数据结构
      for (let i = 1; i <= 7; i++) {
        if (i === 7) {
          // 对于周日，使用 "日" 替代 "七"
          questArr.push({
            title: `周日`,
            width: 80,
            dataIndex: `quest${i}`,
            key: `quest${i}`,
            align: "center",
            render: (value) => {
              return <span className={"template_span"}>{value}</span>;
            },
          });
        } else {
          questArr.push({
            title: `周${'一二三四五六日'[i - 1]}`,
            width: 80,
            dataIndex: `quest${i}`,
            key: `quest${i}`,
            align: "center",
            render: (value) => {
              return <span className={"template_span"}>{value}</span>;
            },
          });
        }
      }
      columns = [...obj, ...questArr];
      // console.log(questArr, 'questArr');
    } else if (props.templateType === 1) {
      let obj = [
        {
          title: `周次`,
          width: 80,
          dataIndex: `weekNo`,
          key: `weekNo`,
          align: "center",
          render: (value) => {
            return <span className={"template_span"}>{value}</span>;
          },
          onCell: (record, index) => {
            // console.log(record, 'record');
            const props = {
              rowSpan: 0,
            };
            if (index === 0) {
              props.rowSpan = 7;
            }
            return props;
          },

        },
        {
          title: `日期`,
          width: 80,
          dataIndex: `day`,
          key: `day`,
          align: "center",
          render: (value) => {
            return <span className={"template_span days_span"}>{value}</span>;
          },
        },
        {
          title: "值日人员",
          width: 302,
          // marginLeft: '29px',
          dataIndex: "grouperPerson",
          key: "grouperPerson",
          align: "center",
          render: (value, record) => {
            return <span className={"template_span person_list person_list_finish"} title={value}>{value}</span>;
          },
        }
      ]
      data.splice(7, 1)
      columns = [...obj];
    } else if (props.templateType === 2) {
      columns = [
        {
          title: `日期`,
          dataIndex: `day`,
          key: `day`,
          align: "center",
          render: (value, record) => {
            return <span className={"template_span days_span"}>{value}</span>;
          },
          // onCell: (record, index) => {
          //   console.log(record, 'record', index);
          //   const props = {
          //     rowSpan: 2,
          //   };
          //   if (index === 0) {
          //     props.rowSpan = 2;
          //   }
          //   return props;
          // },
        },
        {
          title: "值日人员",
          width: 302,
          // marginLeft: '29px',
          dataIndex: "grouperPersonPhone",
          key: "grouperPersonPhone",
          align: "center",
          render: (value, record) => {
            return <span className={"template_span person_list person_list_finish"} title={value}>{value}</span>;
          },
        },
        {
          title: "值日内容",
          width: 302,
          // marginLeft: '29px',
          dataIndex: "dutyContent",
          key: "dutyContent",
          align: "center",
          render: (value, record) => {
            return <span className={"template_span person_list person_list_finish"} title={value}>{value}</span>;
          },
        },

      ]
    }

  } else if (props.type === 'weekTable') {
    let statusArr = [
      {
        title: "状态",
        width: 90,
        dataIndex: "status",
        key: "status",
        align: "center",
        render: (value) => {
          console.log(value, 'value');
          return <span className={"status " + ('status-' + value)}>{value == 0 ? '未发布' : '已发布'}</span>;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        className: "operation-header",
        width: 180,
        align: "center",
        render: (value, record) => {
          // console.log('record',record);
          return (
            <div className={"operation"}>
              {
                record.status == 0 ?
                  <>
                    <LgButton split shapeType='text' type='info' onClick={() => props.editWeek('editWeek', record.info)}>编辑</LgButton>
                    <LgButton split shapeType='text' type='info' onClick={() => props.publish('publish', 1, record.info)}>发布</LgButton>
                    <LgButton split shapeType='text' type='fail' onClick={() => alertPersonArrangement(record.id, 'del')}>删除</LgButton>
                  </>
                  :
                  <>
                    <LgButton split shapeType='text' type='info' onClick={() => props.remindTeacherByPlay(record.id)}>提醒值周</LgButton>
                    <LgButton split shapeType='text' type='fail' onClick={() => alertPersonArrangement(record.id, 'recall')}>撤回</LgButton>
                  </>
              }
            </div>
          );
        },
      },
    ]
    if (props.weeklyPlayList) {
      let titleIndexMap = {}; // 用于跟踪每个 title 的索引和数据属性名

      props.weeklyPlayList.forEach((item, index) => {
        let userNames = (item.personnelList && item.personnelList.map(item => item.userName)) || [];
        let grouperPerson = userNames.join('、');
        let dataOne = {
          key: index,
          weekNo: item.weekNo,
          days: `${moment(item.weekStartTime).format('YYYY/MM/DD')} ~ ${moment(item.weekEndTime).format('YYYY/MM/DD')}`,
          grouper: item.leader.userName,
          grouperPerson,
          personNum: (item?.personnelList && item?.personnelList.length) || 0,
          status: item.releaseStatus,
          id: item.id,
          info: item,
        };

        if (props?.isEasy === false) {
          columns.splice(3, 1);
          let weeklyTermList = item.weeklyTermList;

          weeklyTermList && weeklyTermList.forEach((weeklyItem, idx) => {
            let userNamesString = weeklyItem?.personInfoVoList.map(person => person.userName).join('、');
            let title = weeklyItem.content;

            // 更新或创建 title 对应的索引项
            if (!titleIndexMap[title]) {
              titleIndexMap[title] = {
                dataIndex: `notEasy${index}${idx}`, // 保持与之前的 dataIndex 格式一致
                content: title,
                items: [],
              };
              statusArr.unshift({
                title: weeklyItem.content,
                dataIndex: `notEasy${index}${idx}`, // 保持与之前的 dataIndex 格式一致
                key: `notEasy${index}${idx}`,
                className: "operation-header",
                align: "center",
                render: (value, record) => {
                  return <span className={"template_span person_list person_list_finish"} title={value}>{value || '--'}</span>;
                },
              });
            }

            let dataIndex = titleIndexMap[title].dataIndex; // 获取当前 title 对应的唯一 dataIndex
            // 更新 dataOne 对象
            console.log(dataOne[dataIndex], 'dataOne[dataIndex]');
            dataOne[dataIndex] = userNamesString;
          });
        }

        data.push(dataOne);
      });

      // 扁平化处理 titleIndexMap 的 items 数组，以符合 statusArr 的要求
      statusArr.forEach(item => {
        item.items = item.items ? item.items.flat() : []; // 安全地处理 item.items 可能为 undefined 的情况
      });

      // console.log(data, 'data'); // 输出修改后的 data 数组
      // console.log(statusArr, 'statusArr'); // 输出修改后的 statusArr 数组
    }
    if (props.noOperation) {
      statusArr = statusArr.slice(0, statusArr.length - 2);
    }
    columns = [...columns, ...statusArr];
  } else if (props.type === 'recordTable') {
    columns = [
      {
        width: 90,
        dataIndex: "num",
        key: "num",
        render: (value, record) => {
          return <LgCheckbox className="record_select" disabled={record.beBind === '1' && !record?.canCheck ? true : false} checked={record.checked} label={value} onChange={() => { props.checkRecord(record.key, record.checked) }} />
        },
      },
      {
        title: "值周/值日安排表",
        width: 320,
        dataIndex: "arrangementName",
        key: "arrangementName",
        className: 'arrangement_name',
        render: (value, record) => {
          console.log(record, 'record');
          return <div className={"template_span arrangement_div"}><div className={'left_duty_week ' + (record.typeOf == '1' ? '' : 'left_duty_day')}>{record.typeOf == '1' ? '值周' : '值日'}</div>{value}</div>;
        },
      },
      {
        title: "部门",
        width: 151,
        dataIndex: "departmentName",
        key: "departmentName",
        className: 'arrangement_name',
        render: (value, record) => {
          console.log(record, 'record');
          return <div className={"template_span arrangement_div department_span"}>{value}</div>;
        },
      },
      {
        title: "记录表",
        width: 262,
        dataIndex: "recordMgtName",
        key: "recordMgtName",
        align: "center",
        className: 'arrangement_name',
        render: (value, record) => {
          return <span className={"template_span arrangement_div"}>{record.beBind === '1' ? value : <LgButton type='info' shapeType='text'>待添加记录表</LgButton>}</span>;
        },
      },
    ]
    if (props.recordList) {
      console.log(props.recordList, 'props.WeekOrDayPlayList');
      props.recordList.forEach((item, index) => {
        dataOne = {
          key: index,
          num: index + 1,
          beBind: item.beBind,
          arrangementName: '《' + item.arrangementName + '》',
          departmentName: item?.departmentName || '--',
          recordMgtName: '《' + item.recordMgtName + '》',
          typeOf: item.typeOf,
          checked: item.check,
          info: item,
          canCheck: item.canCheck,
        }
        data.push(dataOne);
        return data;
      })

    }
  } else if (props.type === 'aKey') {
    columns.splice(2)
    let beLeader = props?.beLeader || false
    let personArr = [
      {
        title: "值周组长",
        width: 100,
        dataIndex: "grouper",
        key: "grouper",
        align: "center",
        render: (value) => {
          return <span className={"template_span"} title={value}>{value}</span>;
        },
      },
      {
        title: "值周人员",
        width: 302,
        // marginLeft: '29px',
        dataIndex: "grouperPerson",
        key: "grouperPerson",
        align: "center",
        render: (value, record) => {
          return <span className={"template_span person_list person_list_finish"} title={value}>{value}</span>;
        },
      }
    ]
    let statusArr = []
    if (props?.stepNum !== '3') {
      statusArr = [
        {
          title: "操作",
          dataIndex: "operation",
          key: "operation",
          className: "operation-header",
          width: 120,
          align: "center",
          render: (value, record) => {
            console.log('record', record);
            return (
              <div className={"operation"}>
                <LgButton split shapeType='text' type='info' onClick={() => props.editWeek('editWeeks', record.info, record.key)}>编辑</LgButton>
                <LgButton split shapeType='text' type='fail' onClick={() => delWeek(record.key, 'del')}>删除</LgButton>
              </div>
            );
          },
        },
      ]
    }
    if (!beLeader) {
      personArr.splice(0, 1)
    }

    if (props.AKeyWeekList) {

      console.log(props.AKeyWeekList, 'props.WeekOrDayPlayList1');
      let grouperPerson = '';
      props.AKeyWeekList.forEach((item, index) => {
        if (props.isSetFinish && item?.personnelNameList) {
          grouperPerson = item.personnelNameList.join('、');
        }
        dataOne = {
          key: index,
          weekNo: item.weekNo,
          days: moment(item.weekStartTime).format('YYYY/MM/DD') + '~' + moment(item.weekEndTime).format('YYYY/MM/DD'),
          info: item,
          grouper: item.leaderName,
          grouperPerson,
        }
        if (props?.isEasy === false && props.isSetFinish) {
          personArr.splice(1, 1); // 操作 personArr 数组，这部分逻辑依赖于你的实际需求
          // if (index > 0) return
          let weeklyTermList = item.weeklyTermList; // 假设 item 是从某个地方获取的

          // 处理原始数据，生成目标数组
          weeklyTermList && weeklyTermList.forEach((weeklyItem, idx) => {
            let userNamesString = weeklyItem?.personInfoVoList.map(person => person.userName).join('、');
            dataOne[`notEasy${idx}`] = userNamesString;

            // 构造新对象，插入到 statusArr 中
            if (index < 1) {
              statusArr.unshift({
                title: weeklyItem.content, // 使用 weeklyItem 中的 content 属性
                dataIndex: `notEasy${idx}`,
                key: `notEasy${idx}`,
                className: "operation-header",
                align: "center",
                render: (value, record) => {
                  return <span className={"template_span person_list person_list_finish"} title={value}>{value}</span>;
                },
              });
            }
          });
        }


        if (!props.isSetFinish) {
          delete dataOne.grouperPerson
        }
        data.push(dataOne);
        console.log(data, 'data');
        return data;
      })
      if (props?.stepNum === '3') {
        columns = [...columns, ...personArr, ...statusArr];
      } else {
        columns = [...columns, ...statusArr];
      }
    }
  } else if (props.type === 'aKeyDay') {
    let { explicit, routine, AKeyDayList, stepNum } = props
    console.log(AKeyDayList, 'AKeyDayList', stepNum);
    if (explicit) {
      columns = [{
        title: "日期",
        width: 200,
        dataIndex: "days",
        key: "days",
        align: "center",
        render: (value) => {
          return <span className={"template_span days_span"} title={value} style={{ width: !(userInfo.userType === '6' || (userInfo.userType === '0' && (userInfo.userClass === '2' || userInfo.userClass === '4'))) ? '227px' : '' }} >{value}</span>;
        },
      }]
    } else {
      columns.splice(2)
    }
    let personArr = [
      {
        title: "值日人员",
        width: 302,
        // marginLeft: '29px',
        dataIndex: "grouperPerson",
        key: "grouperPerson",
        align: "center",
        render: (value, record) => {
          return <span className={"template_span person_list person_list_finish"} title={value}>{value}</span>;
        },
      },
      {
        title: "值日内容",
        width: 200,
        dataIndex: "content",
        key: "content",
        align: "center",
        render: (value) => {
          return <span className={"template_span"} title={value}>{value}</span>;
        },
      },
    ]

    let statusArr = []
    if (props?.stepNum !== '3') {
      statusArr = [
        {
          title: "操作",
          dataIndex: "operation",
          key: "operation",
          className: "operation-header",
          width: 120,
          align: "center",
          render: (value, record) => {
            console.log('record', record);
            return (
              <div className={"operation"}>
                <LgButton split shapeType='text' type='info' onClick={() => props.editWeek('editWeeks', record.info, record.key)}>编辑</LgButton>
                <LgButton split shapeType='text' type='fail' onClick={() => delWeek(record.key, 'delDay')}>删除</LgButton>
              </div>
            );
          },
        },
      ]
    }

    if (AKeyDayList) {

      console.log(AKeyDayList, 'props.WeekOrDayPlayList1');
      let grouperPerson = '';
      AKeyDayList.forEach((item, index) => {
        if (props.isSetFinish && item?.personnelNameList) {
          grouperPerson = item.personnelNameList.join('、');
        }
        dataOne = {
          key: index,
          weekNo: item.weekNo,
          days: moment(item.dayTime).format('YYYY/MM/DD'),
          info: item,
          grouper: item.leaderName,
          grouperPerson,
        }
        if (props?.isEasy === false && props.isSetFinish) {
          personArr.splice(1, 1); // 操作 personArr 数组，这部分逻辑依赖于你的实际需求
          // if (index > 0) return
          let weeklyTermList = item.weeklyTermList; // 假设 item 是从某个地方获取的

          // 处理原始数据，生成目标数组
          weeklyTermList && weeklyTermList.forEach((weeklyItem, idx) => {
            let userNamesString = weeklyItem?.personInfoVoList.map(person => person.userName).join('、');
            dataOne[`notEasy${idx}`] = userNamesString;

            // 构造新对象，插入到 statusArr 中
            if (index < 1) {
              statusArr.unshift({
                title: weeklyItem.content, // 使用 weeklyItem 中的 content 属性
                dataIndex: `notEasy${idx}`,
                key: `notEasy${idx}`,
                className: "operation-header",
                align: "center",
                render: (value, record) => {
                  return <span className={"template_span person_list person_list_finish"} title={value}>{value}</span>;
                },
              });
            }
          });
        }


        if (!props.isSetFinish) {
          delete dataOne.grouperPerson
        }
        data.push(dataOne);
        console.log(data, 'data');
        return data;
      })
      if (stepNum === '3') {
        columns = [...columns, ...personArr, ...statusArr];
      } else {
        if (explicit) {
          columns = [...columns, ...statusArr];

        } else {
          columns = [...columns, ...statusArr];
        }
      }
    }
  } else if (props.type === 'recordList') {
    if (props.recordList) {
      console.log(props.recordList, 'props.recordList');
      props.recordList.forEach((item, index) => {
        dataOne = {
          key: index,
          num: index + 1,
          beBind: item.beBind,
          arrangementName: '《' + item.recordMgtName + '》',
          departmentName: item?.departmentName || '--',
          recordMgtName: '《' + item.recordMgtName + '》',
          typeOf: item.typeOf,
          checked: item.check,
          info: item,
        }
        data.push(dataOne);
        return data;
      })

    }
    columns = [
      {
        width: 90,
        dataIndex: "num",
        key: "num",
        render: (value, record) => {
          return <LgRadio.Group value={record.key} >
            <LgRadio className="g006-form-1-item" value={record.key}>{value}</LgRadio>
          </LgRadio.Group>
          //  <LgCheckbox className="record_select" disabled={record.beBind === '1' ? true : false} checked={record.checked} label={value} onChange={() => { if (record.beBind === '0') { props.checkRecord(record.key, record.checked) } }} />

        },
      },
      {
        title: "记录表",
        // width: 511,
        dataIndex: "recordMgtName",
        key: "recordMgtName",
        align: "center",
        className: 'arrangement_name',
        render: (value, record) => {
          return <span className={"template_span arrangement_div"}>{record.beBind === '1' ? value : <LgButton type='info' shapeType='text'>待添加记录表</LgButton>}</span>;
        },
      },
    ]
  } else if (props.type === 'reminderTable') {
    let weekdays = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"];
    if (props.remindList) {
      console.log(props.remindList, 'props.recordList');
      props.remindList.forEach((item, index) => {
        // 将每个数字字符串映射成对应的星期字符串
        const result = item.scopeList.map(numStr => weekdays[parseInt(numStr) - 1]);
        const resultString = result.join('、'); // 用中文顿号连接字符串
        dataOne = {
          key: index,
          num: index + 1,
          remindTime: item.remindDate,
          remindItem: item.remindItem,
          timeRanger: resultString,
          remindId: item.remindId,
          info: item,
        }
        data.push(dataOne);
        return data;
      })

    }
    columns = [
      {
        width: 50,
        dataIndex: "num",
        key: "num",
        align: "center",
        render: (value, record) => {
          return <span className={"template_span num_color"}>{value}</span>
        },
      },
      {
        title: "提醒时间",
        width: 90,
        dataIndex: "remindTime",
        key: "remindTime",
        align: "center",
        className: 'arrangement_name',
        render: (value, record) => {
          return <span className={"template_span arrangement_div"}>{value}</span>;
        },
      },
      {
        title: "提醒事项",
        width: 120,
        dataIndex: "remindItem",
        key: "remindItem",
        align: "center",
        className: 'arrangement_name',
        render: (value, record) => {
          return <span className={"template_span arrangement_div"}>{value}</span>;
        },
      },
      {
        title: "适用时间范围",
        width: 434,
        dataIndex: "timeRanger",
        key: "timeRanger",
        align: "center",
        className: 'arrangement_name',
        render: (value, record) => {
          return <span className={"template_span arrangement_div  num_color"}>{value}</span>;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        className: "operation-header",
        width: 120,
        align: "center",
        render: (value, record) => {
          console.log('record', record);
          return (
            <div className={"operation"}>
              <LgButton split shapeType='text' type='info' onClick={() => props.editRemind('editRemindItem', record.info, record.key)}>编辑</LgButton>
              <LgButton split shapeType='text' type='fail' onClick={() => delRemindItem(record.remindId, 'delRemindItem')}>删除</LgButton>
            </div>
          );
        },
      },
    ]
  } else if (props.type === 'dayTable') {
    let {
      takeTurns,
      routine,
      explicit,
      dayPlayList,
    } = props
    let questArr = [], obj = [];
    console.log(props, 'props', dayPlayList);
    if (takeTurns) {

      if (dayPlayList) {
        dayPlayList.forEach((item, index) => {
          let quests = ['', '', '', '', '', '', ''];
          let questsPersonNum = [0, 0, 0, 0, 0, 0, 0];
          item.dutyDetailList.forEach(detail => {
            // 初始化 quests 数组，用于存放 quest1 到 quest7 的值
            // 找到对应的 week 在 quests 中的索引
            let weekIndex = parseInt(detail.week) - 1;
            questsPersonNum[weekIndex] += detail.dutyPersonList.length

            // 将 dutyPersonList 中的 userName 添加到 quests[weekIndex] 中
            detail.dutyPersonList.forEach((person, idx) => {
              if (weekIndex >= 0 && weekIndex < 7) { // 确保 weekIndex 在合法范围内
                if (quests[weekIndex] === '') {
                  quests[weekIndex] += person.userName;
                } else {
                  quests[weekIndex] += '、' + person.userName;
                }
              }
            });

            // 构建 dataOne 对象并添加到 data 数组中
          });
          let dataOne = {
            key: index,
            num: index + 1,
            group: item.dutyGroupName,
            quest1: quests[0],
            quest2: quests[1],
            quest3: quests[2],
            quest4: quests[3],
            quest5: quests[4],
            quest6: quests[5],
            quest7: quests[6],
            questsPersonNum: questsPersonNum,
            status: item.releaseStatus,
            currentWeekUseStatus: item.currentWeekUseStatus,
            id: item.id,
            info: item // 将原始 detail 对象存入 info 字段中
          };

          data.push(dataOne);
        });
      }
      console.log(data, 'data');
      obj = [
        {
          title: `组别`,
          width: 80,
          dataIndex: `group`,
          key: `group`,
          align: "center",
          render: (value, record) => {
            return <span className={"template_span"}>{value}<span style={{ color: '#ff6600' }}>{record.currentWeekUseStatus === '1' ? '（本周）' : ''}</span></span>;
          },
        }
      ]
      // 生成从周一到周日的数据结构
      for (let i = 1; i <= 7; i++) {
        if (i === 7) {
          // 对于周日，使用 "日" 替代 "七"
          questArr.push({
            title: `周日`,
            width: 80,
            dataIndex: `quest${i}`,
            key: `quest${i}`,
            align: "center",
            render: (value) => {
              return <span className={"template_span " + (value ? (isManage != '1' ? 'have_value have_value_teacher' : 'have_value') : 'no_value')} title={value ? value : '--'} >{value ? value : '--'}</span>;
            },
          });
        } else {
          questArr.push({
            title: `周${'一二三四五六日'[i - 1]}`,
            width: 80,
            dataIndex: `quest${i}`,
            key: `quest${i}`,
            align: "center",
            render: (value, record) => {
              return <span style={{ display: 'flex', color: '#333', whiteSpace: 'nowrap' }}><span className={"template_span " + (value ? (isManage != '1' ? 'have_value have_value_teacher' : 'have_value') : 'no_value')} title={value ? value : '--'}>{value ? value : '--'}</span><span>{value.length > 9 ? `等${record.questsPersonNum[i - 1]}人` : ''}</span></span>;
            },
          });
        }
      }
    }
    if (routine) {
      if (dayPlayList) {
        dayPlayList.forEach((item, index) => {
          let userNames = (item.personnelList && item.personnelList.map(item => item.userName)) || item?.personnelNameList || [];
          let grouperPerson = userNames.join('、');
          // 构建 dataOne 对象并添加到 data 数组中
          let dataOne = {
            key: index,
            num: index + 1,
            grouperPerson: grouperPerson,
            day: moment(item.dayTime).format('YYYY-MM-DD') + '       ' + getChineseDayOfWeek(item.dayTime),
            group: item.dutyGroupName,
            status: item.releaseStatus,
            id: item.id,
            weekNo: item.weekNo,
            personNum: (item?.personnelList && item?.personnelList.length) || 0,
            info: item, // 将原始 detail 对象存入 info 字段中
          };
          data.push(dataOne);
        });
      }
      console.log(data, 'data');
      obj = [
        {
          title: `周次`,
          dataIndex: `weekNo`,
          key: `weekNo`,
          align: "center",
          width: 80,
          render: (value, record) => {
            return <span className={"template_span"}>{value}</span>;
          },
          onCell: (record, index) => {
            // console.log(record, 'record', index);
            const props = {
              rowSpan: 0,
            };
            // 寻找当前记录在数据源中第一个出现的索引
            let startIndex = data.findIndex(item => item.weekNo === record.weekNo);

            // 如果当前记录是该 `weekNo` 值第一次出现的位置，则设置对应的 rowSpan
            if (startIndex !== -1 && index === startIndex) {
              // 计算该 `weekNo` 值在数据源中的数量
              let count = data.filter(item => item.weekNo === record.weekNo).length;
              props.rowSpan = count;
            }
            return props;
          },
        },
        {
          title: `日期`,
          dataIndex: `day`,
          key: `day`,
          align: "center",
          width: 280,
          render: (value, record) => {
            return <span className={"template_span days_span"}>{value}</span>;
          },
        },
        {
          title: "值日人员",
          // width: 302,
          // marginLeft: '29px',
          dataIndex: "grouperPerson",
          key: "grouperPerson",
          align: "center",
          render: (value, record) => {
            return <span style={{ display: 'flex', color: '#333' }}><span className={"template_span person_list person_list_finish day_person_list"} title={value}>{value}</span><span> {value.length > 34 ? `等${record.personNum}人` : ''}</span></span>;
          },
        },
      ]
      // 生成从周一到周日的数据结构

    }
    if (explicit) {

      if (dayPlayList) {
        dayPlayList.forEach((item, index) => {
          item.dutyTermList.forEach(detail => {
            let userNamesWithPhones = (detail.personInfoVoList || []).map(item => {
              // 假设电话号码字段为 telephone，如果电话号码为空则显示空字符串
              let phone = item.telephone || item.telephone2 || '';
              return `${item.userName} ${phone}`;  // 每个人名后面加上电话号码
            });
            let grouperPerson = userNamesWithPhones.join('、');

            // 构建 dataOne 对象并添加到 data 数组中
            let dataOne = {
              key: index,
              num: index + 1,
              grouperPersonPhone: grouperPerson,
              day: moment(item.dayTime).format('YYYY-MM-DD'),
              group: item.dutyGroupName,
              dutyContent: detail.content,
              id: item.id,
              status: item.releaseStatus,
              personNum: (detail.personInfoVoList && detail.personInfoVoList.length) || 0,
              info: item, // 将原始 detail 对象存入 info 字段中
            };
            data.push(dataOne);
          });

        });
      }
      data.forEach((item, idx) => {
        item.key = idx
      })
      obj = [
        {
          title: `日期`,
          dataIndex: `day`,
          key: `day`,
          align: "center",
          width: 152,
          render: (value, record) => {
            return <span className={"template_span days_span"}>{value}</span>;
          },
          onCell: (record, index) => {
            // console.log(record, 'record', index);
            const props = {
              rowSpan: 0,
            };
            // 寻找当前记录在数据源中第一个出现的索引
            let startIndex = data.findIndex(item => item.num === record.num);

            // 如果当前记录是该 `num` 值第一次出现的位置，则设置对应的 rowSpan
            if (startIndex !== -1 && index === startIndex) {
              // 计算该 `num` 值在数据源中的数量
              let count = data.filter(item => item.num === record.num).length;
              props.rowSpan = count;
            }
            return props;
          },
        },
        {
          title: "值日人员",
          // width: 302,
          // marginLeft: '29px',
          dataIndex: "grouperPersonPhone",
          key: "grouperPersonPhone",
          align: "center",
          render: (value, record) => {
            return <span style={{ display: 'flex', color: '#333' }}><span className={"template_span person_list person_list_finish day_person_list"} title={value}>{value}</span><span> {value.length > 34 ? `等${record.personNum}人` : ''}</span></span>;
          },
        },
        {
          title: "值日内容",
          width: 302,
          // marginLeft: '29px',
          dataIndex: "dutyContent",
          key: "dutyContent",
          align: "center",
          render: (value, record) => {
            return <span className={"template_span person_list person_list_finish"} title={value}>{value}</span>;
          },
        },
      ]
      // 生成从周一到周日的数据结构

    }
    let statusArr = [
      {
        title: "状态",
        width: 90,
        dataIndex: "status",
        key: "status",
        align: "center",
        render: (value) => {
          console.log(value, 'value');
          return <span className={"status " + ('status-' + value)}>{value == 0 ? '未发布' : '已发布'}</span>;
        },
        onCell: (record, index) => {
          // console.log(record, 'record', index);
          if (!explicit) return
          const props = {
            rowSpan: 0,
          };
          // 寻找当前记录在数据源中第一个出现的索引
          let startIndex = data.findIndex(item => item.num === record.num);

          // 如果当前记录是该 `num` 值第一次出现的位置，则设置对应的 rowSpan
          if (startIndex !== -1 && index === startIndex) {
            // 计算该 `num` 值在数据源中的数量
            let count = data.filter(item => item.num === record.num).length;
            props.rowSpan = count;
          }
          return props;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        className: "operation-header",
        width: 180,
        align: "center",
        render: (value, record) => {
          // console.log('record',record);
          return (
            <div className={"operation"}>
              {

                props?.stepNum === '3' ?
                  <>
                    <LgButton split shapeType='text' type='info' onClick={() => props.publish('publish', 1, record.info)}>编辑</LgButton>
                    <LgButton split shapeType='text' type='fail' onClick={() => alertPersonArrangement(record.id, 'del')}>删除</LgButton>
                  </>
                  :
                  record.status == 0 ?
                    <>
                      <LgButton split shapeType='text' type='info' onClick={() => props.editWeek(takeTurns ? 'takeTurnsEdit' : routine ? 'routineEdit' : 'explicitEdit', record.info)}>编辑</LgButton>
                      <LgButton split shapeType='text' type='info' onClick={() => props.publish('publish', 1, record.info)}>发布</LgButton>
                      <LgButton split shapeType='text' type='fail' onClick={() => alertPersonArrangement(record.id, 'del')}>删除</LgButton>
                    </>
                    :
                    <>
                      <LgButton split shapeType='text' type='info' onClick={() => props.remindTeacherByPlay(record.id)}>提醒值日</LgButton>
                      <LgButton split shapeType='text' type='fail' onClick={() => alertPersonArrangement(record.id, 'recall')}>撤回</LgButton>
                    </>
              }
            </div>
          );
        },
        onCell: (record, index) => {
          // console.log(record, 'record', index);
          if (!explicit) return
          const props = {
            rowSpan: 0,
          };
          // 寻找当前记录在数据源中第一个出现的索引
          let startIndex = data.findIndex(item => item.num === record.num);

          // 如果当前记录是该 `num` 值第一次出现的位置，则设置对应的 rowSpan
          if (startIndex !== -1 && index === startIndex) {
            // 计算该 `num` 值在数据源中的数量
            let count = data.filter(item => item.num === record.num).length;
            props.rowSpan = count;
          }
          return props;
        },
      },
    ]
    if (props?.stepNum === '3') {
      // statusArr.splice(0, 1)
      statusArr.splice(0)
    }
    if (!props?.noOperation) {
      columns = [...obj, ...questArr, ...statusArr];
    } else {
      columns = [...obj, ...questArr];
    }
  } else if (props.type === 'workload') {
    let childrenDay = [], childrenWeek = [];
    let workload = props.workload;
    console.log(workload, 'workload1');
    let weekDetailList = [
      {
        content: '扫地',
        times: '1'
      },
      {
        content: '擦黑板',
        times: '3'
      },
      {
        content: '洗厕所',
        times: '54'
      },
    ]
    workload && workload.forEach((item, index) => {
      let dataOne = {};
      // item.dayDetailList = weekDetailList;
      // item.weekDetailList = weekDetailList
      dataOne = {
        key: index,
        totalTimes: item.totalTimes,
        totalTimesForDay: item.totalTimesForDay,
        totalTimesForWeek: item.totalTimesForWeek,
        userName: item.userName,
        userId: item.userId,
        avatar: item.avatar,
      };
      if ((Array.isArray(item?.dayDetailList) && item?.dayDetailList.length > 0) || (Array.isArray(item?.weekDetailList) && item?.weekDetailList.length > 0)) {
        childrenDay = item.dayDetailList.map((item, index) => ({
          title: item.content,  // title 使用 content
          dataIndex: `day${index}`,  // 使用 day + index 作为唯一的 dataIndex
          key: `day${index}`,  // 使用 day + index 作为唯一的 key
          align: 'center',  // 固定的 align 属性
          render: (value) => {  // 如果需要特殊的 render，可以在这里添加
            return <span className={styles["principal"]}><LgButton textUnderline type='info' shapeType='text'>{value}</LgButton></span>;
          },
        }));
        childrenWeek = item.weekDetailList.map((item, index) => ({
          title: item.content + '1',  // title 使用 content
          dataIndex: `week${index}`,  // 使用 week + index 作为唯一的 dataIndex
          key: `week${index}`,  // 使用 week + index 作为唯一的 key
          align: 'center',  // 固定的 align 属性
          render: (value) => {  // 如果需要特殊的 render，可以在这里添加
            return <span className={styles["principal"]}><LgButton textUnderline type='info' shapeType='text'>{value}</LgButton></span>;
          },
        }));

        item.dayDetailList.forEach((itm, idx) => {
          dataOne[`day${idx}`] = itm.times;
        });
        item.weekDetailList.forEach((itm, idx) => {
          dataOne[`week${idx}`] = itm.times;
        });
      }
      data.push(dataOne)
    })

    columns = [
      {
        title: "姓名",
        dataIndex: "userName",
        key: "userName",
        width: 200,
        align: "center",
        render: (value, record) => {
          return <div className='user_name'><i className="user_photo" style={{ backgroundImage: `url(${record.avatar})` }}></i><span>{value}<span style={{ color: '999' }}>{'(' + record.userId + ')'}</span></span></div>;
        },
      },
      {
        title: "总数",
        dataIndex: "totalTimes",
        key: "totalTimes",
        align: "center",
        render: (value, record) => {  // 如果需要特殊的 render，可以在这里添加
          return <span className={styles["principal"]}>{value == 0 ? value : <LgButton textUnderline type='info' shapeType='text' onClick={() => props.getWorkloadDetail(record, '')} >{value}</LgButton>}</span>;
        },
      },
      {
        title: "值周次数",
        dataIndex: "totalTimesForWeek",
        key: "totalTimesForWeek",
        align: "center",
        render: (value, record) => {  // 如果需要特殊的 render，可以在这里添加
          return <span className={styles["principal"]}>{value == 0 ? value : <LgButton textUnderline type='info' shapeType='text' onClick={() => props.getWorkloadDetail(record, '1')}>{value}</LgButton>}</span>;
        },
        // children: childrenWeek,
      },
      {
        title: "值日次数",
        dataIndex: "totalTimesForDay",
        key: "totalTimesForDay",
        align: "center",
        render: (value, record) => {  // 如果需要特殊的 render，可以在这里添加
          return <span className={styles["principal"]}>{value == 0 ? value : <LgButton textUnderline type='info' shapeType='text' onClick={() => props.getWorkloadDetail(record, '2')}>{value}</LgButton>}</span>;
        },
        // children: childrenDay,
      },
    ]
  } else if (props.type === 'contentTable') {
    let {
      contentList,
      isWeek,
    } = props
    contentList && contentList.forEach((item, index) => {
      let dataOne = {
        key: index,
        num: index + 1,
        content: item?.content,
        require: item?.require,
      };
      data.push(dataOne);
    })

    columns = [
      {
        title: "",
        dataIndex: "num",
        key: "num",
        width: 50,
        align: "center",
        render: (value, record) => {
          return <div className='content_num'>{value}</div>;
        },
      },
      {
        title: `值${isWeek}内容`,
        dataIndex: "content",
        width: 120,
        key: "content",
        align: "center",
        render: (value, record) => {
          return <div className={"template_span content_span"} title={value}>{value}</div>;
        },
      },
      {
        title: `值${isWeek}要求`,
        dataIndex: "require",
        key: "require",
        align: "center",
        width: 523,
        render: (value, record) => {
          return <div className={"template_span require_span"} title={value}>{value}</div>;
        },
      },
      {
        title: "操作",
        dataIndex: "operation",
        key: "operation",
        className: "operation-header",
        width: 120,
        align: "center",
        render: (value, record) => {
          console.log('record', record);
          return (
            <div className={"operation"}>
              <LgButton split shapeType='text' type='info' onClick={() => props.editContent(record)}>编辑</LgButton>
              <LgButton split shapeType='text' type='fail' onClick={() => props.alertDelete(record, 'delContent')}>删除</LgButton>
            </div>
          );
        },
      },
    ]
  } else if (props.type === 'workloadList') {
    let {
      detailList,
    } = props

    // 新增过滤逻辑
    detailList = detailList.filter(item =>
      (item.typeOf === '1' || item.typeOf === '2') &&
      (item.content !== '值周老师' && item.content !== '值日老师')
    );

    detailList && detailList.forEach((item, index) => {
      let dataOne = {
        key: index,
        num: index + 1,
        time: moment(item?.time).format('YYYY-MM-DD') + `（${getChineseDayOfWeek(item?.time)}）`,
        type: item?.typeOf == '1' ? '值周' : '值日',
        content: item?.content,
      };
      data.push(dataOne);
    })

    columns = [
      {
        title: "",
        dataIndex: "num",
        key: "num",
        width: 60,
        align: "center",
        render: (value, record) => {
          return <div className='content_num'>{value}</div>;
        },
      },
      {
        title: `时间`,
        dataIndex: "time",
        width: 320,
        key: "time",
        align: "center",
        render: (value, record) => {
          return <div className={"template_span time_span"} title={value}>{value}</div>;
        },
      },
      {
        title: `类型`,
        dataIndex: "type",
        key: "type",
        align: "center",
        width: 151,
        render: (value, record) => {
          return <div className={"template_span type_span"} title={value}>{value}</div>;
        },
      },
      {
        title: `内容`,
        dataIndex: "content",
        key: "content",
        align: "center",
        width: 262,
        render: (value, record) => {
          return <div className={"template_span content_span_work"} title={value}>{value}</div>;
        },
      },
    ]
  }
  function getChineseDayOfWeek(dayTime) {
    const daysOfWeek = ['日', '一', '二', '三', '四', '五', '六',];
    const dateObj = new Date(dayTime);

    if (isNaN(dateObj)) {
      return "无效日期";
    }

    const dayIndex = dateObj.getDay();
    return `周${daysOfWeek[dayIndex]}`;
  };

  // 辅助函数：将日期格式化为 'YYYY/MM/DD' 的字符串
  function formatDate(date) {
    return `${date.getFullYear()}/${padZero(date.getMonth() + 1)}/${padZero(date.getDate())}`;
  }

  // 辅助函数：在日期上添加指定天数
  function addDays(date, days) {
    let result = new Date(date);
    result.setDate(result.getDate() + days);
    return result;
  }

  // 辅助函数：补零到两位数
  function padZero(num) {
    return num < 10 ? `0${num}` : num;
  }
  // console.log(data, '1234561', columns);
  return (
    <div>
      {/* <h4>基础表格</h4> */}
      {
        props?.noScroller ?
          <LgTable columns={columns} data={data} emptyText={(props.type === 'weekTable' || props.type === 'aKey' || props.type === 'contentTable') && props?.emptyText ? props?.emptyText : '暂无安排信息'} bordered />
          :
          <Scrollbars autoHeight autoHeightMax={props?.autoHeightMax ? props.autoHeightMax : 592} autoHide autoHideTimeout={100}>
            <LgTable columns={columns} data={data} emptyText={(props.type === 'weekTable' || props.type === 'aKey') && props?.emptyText ? props?.emptyText : '暂无安排信息'} bordered />
          </Scrollbars>
      }
    </div>
  );
};

export default Base;